<script setup lang="ts">
import Milkdown from "@/components/MilkdownEditor.vue";
import { MilkdownProvider } from "@milkdown/vue";
import { ref, onMounted } from "vue";
import { toast } from "./utils/toast/toast";
import "./utils/toast/toast.css";
import "./style.css";
import Header from "./components/header/Header.vue";
import { PrintToPDFOptions } from "electron";

const currentFilePath = ref<string | null>(null);

const dirty = ref(false);
const currentFileContent = ref("");
const handleChange = () => {
  dirty.value = true;
};

const saveFile = async () => {
  try {
    const content = currentFileContent.value;

    if (currentFilePath.value) {
      // 如果有当前文件路径，直接保存
      await window.electronAPI.fs.writeFile(currentFilePath.value, content);
      dirty.value = false;
      toast.success("保存成功");
    } else {
      // 如果没有当前文件路径，弹出保存对话框
      const result = await window.electronAPI.dialog.saveFile("untitled.md");
      if (!result.canceled && result.filePath) {
        await window.electronAPI.fs.writeFile(result.filePath, content);
        dirty.value = false;
        toast.success("保存成功");
        currentFilePath.value = result.filePath;
      }
    }
  } catch (error) {
    toast.error("保存文件失败");
    console.error(error);
  }
};

const saveFileAs = async () => {
  try {
    const content = currentFileContent.value;
    const result = await window.electronAPI.dialog.saveFile(
      currentFilePath.value || "untitled.md"
    );

    if (!result.canceled && result.filePath) {
      await window.electronAPI.fs.writeFile(result.filePath, content);
      dirty.value = false;
      toast.success("另存为成功");
      currentFilePath.value = result.filePath;
    }
  } catch (error) {
    toast.error("另存为文件失败");
    console.error(error);
  }
};

const exportToPDF = async () => {
  try {
    const result = await window.electronAPI.file.exportPDF(
      (currentFilePath.value || "exports").replace(/\.md$/, ".pdf"),
      {
        landscape: false,
        marginsType: 0,
        printBackground: true,
        pageSize: "A4",
        printSelectionOnly: false,
        preferCSSPageSize: true,
      }
    );

    if (!result.canceled && result.filePath) {
      toast.success("导出PDF成功");
    }
  } catch (error) {
    toast.error("导出PDF失败");
    console.error(error);
  }
};

const openFile = async (filePath: string) => {
  try {
    const result = await window.electronAPI.fs.readFile(filePath);
    if (result.success) {
      currentFilePath.value = filePath;
      currentFileContent.value = result.content ?? "";
      dirty.value = false;
    }
  } catch (error) {
    toast.error("打开文件失败");
    console.error(error);
  }
};

onMounted(() => {
  // 监听来自主进程的保存事件
  window.electronAPI.on("file:save", () => {
    saveFile();
  });

  window.electronAPI.on("file:save-as", () => {
    saveFileAs();
  });

  window.electronAPI.on("file:opened", (_event, filePath: string) => {
    openFile(filePath);
  });

  window.electronAPI.on("file:new-created", (_event, filePath: string) => {
    currentFilePath.value = filePath;
    currentFileContent.value = "";
  });

  window.electronAPI.on("file:export-pdf", (_event) => {
    exportToPDF();
  });
});
</script>

<template>
  <Header :currentFilePath="currentFilePath" :dirty="dirty" />
  <MilkdownProvider>
    <Milkdown
      :key="currentFilePath ?? 'untitled.md'"
      v-model:modelValue="currentFileContent"
      @update:modelValue="handleChange"
    />
  </MilkdownProvider>
</template>
